"""权限控制模块 - 使用Django内建权限系统"""
from rest_framework import permissions
from django.contrib.auth.models import Permission


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    自定义权限：只有对象的所有者才能编辑它
    """

    def has_object_permission(self, request, view, obj):
        # 读取权限允许任何请求
        # 所以我们总是允许GET、HEAD或OPTIONS请求
        if request.method in permissions.SAFE_METHODS:
            return True

        # 写入权限只给对象的所有者
        return obj.owner == request.user


class IsAdminOrReadOnly(permissions.BasePermission):
    """
    自定义权限：只有管理员才能编辑，其他用户只读
    """

    def has_permission(self, request, view):
        # 读取权限允许任何已认证用户
        if request.method in permissions.SAFE_METHODS:
            return request.user and request.user.is_authenticated

        # 写入权限只给管理员
        return request.user and request.user.is_staff


class IsOwnerOrAdmin(permissions.BasePermission):
    """
    自定义权限：只有对象的所有者或管理员才能访问
    """

    def has_object_permission(self, request, view, obj):
        # 管理员有所有权限
        if request.user and request.user.is_staff:
            return True

        # 对象所有者有所有权限
        return hasattr(obj, 'owner') and obj.owner == request.user


class IsSelfOrAdmin(permissions.BasePermission):
    """
    自定义权限：只有用户自己或管理员才能访问用户信息
    """

    def has_object_permission(self, request, view, obj):
        # 管理员有所有权限
        if request.user and request.user.is_staff:
            return True

        # 用户只能访问自己的信息
        return obj == request.user


class DjangoModelPermissions(permissions.DjangoModelPermissions):
    """
    扩展的Django模型权限检查
    """
    perms_map = {
        'GET': [],
        'OPTIONS': [],
        'HEAD': [],
        'POST': ['%(app_label)s.add_%(model_name)s'],
        'PUT': ['%(app_label)s.change_%(model_name)s'],
        'PATCH': ['%(app_label)s.change_%(model_name)s'],
        'DELETE': ['%(app_label)s.delete_%(model_name)s'],
    }


class DjangoModelPermissionsWithView(DjangoModelPermissions):
    """
    Django模型权限检查 - 包含查看权限
    """
    perms_map = {
        'GET': ['%(app_label)s.view_%(model_name)s'],
        'OPTIONS': [],
        'HEAD': [],
        'POST': ['%(app_label)s.add_%(model_name)s'],
        'PUT': ['%(app_label)s.change_%(model_name)s'],
        'PATCH': ['%(app_label)s.change_%(model_name)s'],
        'DELETE': ['%(app_label)s.delete_%(model_name)s'],
    }


class HasSpecificPermission(permissions.BasePermission):
    """
    检查用户是否有特定权限
    """
    permission_required = None

    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False

        # 超级用户拥有所有权限
        if request.user.is_superuser:
            return True

        if not self.permission_required:
            return True

        return request.user.has_perm(self.permission_required)


class HasAnyPermission(permissions.BasePermission):
    """
    检查用户是否有任意一个指定权限
    """
    permissions_required = []

    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False

        # 超级用户拥有所有权限
        if request.user.is_superuser:
            return True

        if not self.permissions_required:
            return True

        return any(request.user.has_perm(perm) for perm in self.permissions_required)


class HasAllPermissions(permissions.BasePermission):
    """
    检查用户是否有所有指定权限
    """
    permissions_required = []

    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False

        # 超级用户拥有所有权限
        if request.user.is_superuser:
            return True

        if not self.permissions_required:
            return True

        return all(request.user.has_perm(perm) for perm in self.permissions_required)


def create_permission_class(permission_codename):
    """
    动态创建权限检查类
    """
    class DynamicPermission(HasSpecificPermission):
        permission_required = permission_codename

    return DynamicPermission


def create_group_permission_class(group_name):
    """
    动态创建组权限检查类
    """
    class GroupPermission(permissions.BasePermission):
        def has_permission(self, request, view):
            if not request.user or not request.user.is_authenticated:
                return False

            # 超级用户默认属于所有组
            if request.user.is_superuser:
                return True

            return request.user.groups.filter(name=group_name).exists()

    return GroupPermission
